﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Dynamic;
using FluorineFx.Json;

namespace lxwmvc
{
    /// <summary>
    /// 提现功能
    /// </summary>
    public static partial class huifucontroller
    {

        /// <summary>

        /// </summary>
        /// <param name="pb"></param>
        //public static void huifu_chongzhi(pagebase pb)
        //{
            
        //}

        #region 取现部分.s
        /// <summary>
        /// 银行提现获取基本数据
        /// </summary>
        [json]
        public static void user_tixian_data(pagebase pb)
        {
            BaseJson json = pb.JSON<BaseJson>();

            string zongjine = "";
            string dongjieyue = "";

            string yue = huifu_chaxun_yue(core_user.userID, out zongjine, out dongjieyue, false);

            json.data = new
                {
                    UsrBalance = yue,
                    UsrBalance_jine = yue.todecimal(0),
                    //取银行信息，不优化语句了。
                    BankInfo = queryhelper.query(" select SysUser_Bankid,BankTypeid,SysUser_BankType.BankType,(select SUBSTRING(BankCardNum,13,16)) as BankCardNum  FROM SysUser_Bank INNER JOIN SysUser_BankType  ON SysUser_BankType.SysUser_BankTypeid=SysUser_Bank.BankTypeid where user_id='" + core_user.userID +"' order by UseDefault")
                };
            
        }

        #region 计算取现手续费

        /// <summary>
        /// 计算取现手续费
        /// </summary>
        /// <returns></returns>
        static string user_tixian_data_sxf_data(pagebase pb)
        {
            string sxf = "";
            var jine = pb.v_dec("jine");
            string userid = core_user.userID;
            //充值金额
            //Decimal chongzhisum = queryhelper.@object("select SUM(TransAmt) from Msavemoney where User_Id='" + userid + "' and LogType=1").todecimal();
            //债权转让金额
            Decimal zhaiquansum = queryhelper.get("select SUM(CreditDealAmt) from Mzhaiquanliushui where User_Id='" + userid + "' and LogType=1").todecimal();
            //投资金额
            Decimal touzisum = queryhelper.get("select SUM(TransAmt) from Mmanualbid where User_Id='" + userid + "' and LogType=1").todecimal();
            //取现金额
            Decimal quxiansum = queryhelper.get("select SUM(TransAmt) from Mdrawmoney where User_Id='" + userid + "' and LogType=1").todecimal();
            //还款金额
            Decimal fangkuansum = queryhelper.get("select SUM(TransAmt) from Mautoappropriation where User_Id='" + userid + "' and LogType=1").todecimal();
            //标的奖励金额
            Decimal biaodijianglisum = queryhelper.get("select SUM(money) from pbiaodijiangli where UserID='" + userid + "' and Status=1").todecimal();
            //还款利息总和
            Decimal huankuanglixisum = queryhelper.get("select SUM(interest) from PBenefitPlan where User_Id='" + userid + "' and PlanStatus=2").todecimal();

            //可提现金额
            Decimal ketixianjine = (biaodijianglisum + fangkuansum + touzisum + zhaiquansum + huankuanglixisum) - quxiansum;//可提现金额=(标的奖励总和+还款总和+投资总和+债权总和+已还款利息总和)-提现总和

            //提现金额大于不收取手续费的可提现金额
            if (jine > ketixianjine) 
            {
                //2元一笔
                sxf = (2 + ((jine - ketixianjine) * (Decimal.Parse(HuiFuArg.CashFee)))).ToString("#0.00");//商户收取服务费金额
            }
            else
            {
                sxf = "0.00";
            }

            //收取服务费不能大于提现金额的1%
            Decimal maxfuwufei = (jine * Decimal.Parse("0.01"));
            if (Decimal.Parse(sxf) > maxfuwufei)
            {
                sxf = maxfuwufei.ToString("#0.00");
            }
            //这是张明，不收取手续费
            if (userid == "1972")
            {
                sxf = "0.00";
            }

            return sxf;
            //Response.Write(sxf);
        }
        /// <summary>
        /// 输出手续费
        /// </summary>
        /// <param name="pb"></param>
        public static void user_tixian_data_sxf(pagebase pb)
        {
            pb.write(
                user_tixian_data_sxf_data(pb)
                );
        }
        #endregion

        /// <summary>
        /// 用户提现提交到汇付网站
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_tixian_submit(pagebase pb)
        {            
            Cash objsend = new Cash();

            //获取用户信息
            supermodel userinfo = core_user.getUserInfo();

            //获取银行卡信息
            objsend.OpenAcctId = supermodel.create("SysUser_Bank")
                .select("BankCardNum")
                .where("SysUser_Bankid=" + pb.v_i("bank"))
                .one<string>();

            objsend.UsrCustId = userinfo["UsrCustId"] + "";
            //提现金额
            objsend.TransAmt = pb.v_dec("jine").ToString("#0.00");//取现的金额数

            //计算争取的手续费
            var sxf1 = user_tixian_data_sxf_data(pb).todecimal(0).ToString("#0.00");
            var sxf2 = pb.v_dec("hidsxf").ToString("#0.00");
            if (sxf1 != sxf2) throw new Exception("手续费计算有错误!");

            objsend.ServFee = sxf2;
            objsend.ServFeeAcctId = HuiFuArg.AcctId;//商户用来收取服务费的子账号
            
            //插入到提现流水表中
            supermodel Mdrawmoney = supermodel.create("Mdrawmoney");
            Mdrawmoney["User_Id"] = core_user.userID;
            Mdrawmoney["SetupDate"] = DateTime.Now;
            Mdrawmoney["LogType"] = 0;
            Mdrawmoney["OrdId"] = objsend.OrdId + "";
            Mdrawmoney["TransAmt"] = objsend.TransAmt;
            //lxw 20141108 添加.s
            Mdrawmoney["maxid"] = pb.v_s("maxid");
            Mdrawmoney["ServFee"] = objsend.ServFee;
            Mdrawmoney["ServFeeAcctId"] = HuiFuArg.AcctId;//商户用来收取服务费的子账号
            //lxw 20141108 添加.e

            //data["GateBusiId"] = DateTime.Now;
            //data["OpenBankId"] = DateTime.Now;
            //data["DcFlag"] = DateTime.Now;

            //data["TrxId"] = DateTime.Now;
            var ret = Mdrawmoney.saveorupdate();

            //插入成功后，把流水的ID传递到实体中
            objsend.MerPriv = ret.identity + "";
            objsend.BgRetUrl = HuiFuArg.LocalUrl + "huifu/huifu_tixian_submit_returnbg";
            objsend.RetUrl = HuiFuArg.LocalUrl + "huifu/huifu_tixian_submit_return";
            core_huifu.Submit(objsend);
        }

        /// <summary>
        /// 商户代用户取现
        /// </summary>
        public static void huifu_tixian_shanghu(pagebase pb)
        {
            int userid = pb.v_i("userid");
            decimal jine = pb.v_dec("jine");
            MerCash objsend = new MerCash();

            supermodel userinfo = core_user.getUserInfo(userid+"");
            objsend.UsrCustId = userinfo["UsrCustId"] + "";
            //提现金额
            objsend.TransAmt = jine.todecimal().ToString("#0.00");//取现的金额数
            //插入到提现流水表中
            supermodel Mdrawmoney = supermodel.create("Mdrawmoney");
            Mdrawmoney["User_Id"] = userid;
            Mdrawmoney["SetupDate"] = DateTime.Now;
            Mdrawmoney["LogType"] = 0;
            Mdrawmoney["OrdId"] = objsend.OrdId + "";
            Mdrawmoney["TransAmt"] = objsend.TransAmt;
            //lxw 20141108 添加.s
            Mdrawmoney["maxid"] = pb.v_s("maxid");
            Mdrawmoney["ServFee"] = pb.v_s("hidsxf").todecimal().ToString("#0.00");
            Mdrawmoney["ServFeeAcctId"] = HuiFuArg.AcctId;//商户用来收取服务费的子账号
            //lxw 20141108 添加.e

            //data["GateBusiId"] = DateTime.Now;
            //data["OpenBankId"] = DateTime.Now;
            //data["DcFlag"] = DateTime.Now;
            //data["TrxId"] = DateTime.Now;
            var ret = Mdrawmoney.saveorupdate();
            //插入成功后，把流水的ID传递到实体中
            objsend.MerPriv = ret.identity + "";
            objsend.BgRetUrl = HuiFuArg.LocalUrl + "huifu/huifu_tixian_shanghu_returnbg";
            objsend.RetUrl = HuiFuArg.LocalUrl + "huifu/huifu_tixian_shanghu_return";
            core_huifu.Submit(objsend);
        }


        /// <summary>
        /// 商户提现成功显示页面
        /// </summary>
        public static void huifu_tixian_shanghu_return(pagebase pb)
        {
            RetMerCash objrev = new RetMerCash();
            //后台调用，最终要打印出来参数
            core_huifu.ReturnUrl(HttpContext.Current, "RECV_ORD_ID", objrev, false);
            

            //代表成功！
            if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
            {

                //取现成功。判断这条流水是否已经被处理，已经被处理，不能再重复处理
                //objsend.MerPriv这个就是取现流水的ID
                //减少用户的资金
                //设置资金的标示
                huifu_tixian_shanghu_fun(objrev);
                //JSHelper.Redirect("/PUser/message.html?status=1&msg=Cash");
            }
            else
            {
                //JSHelper.Redirect("/PUser/message.html?status=0&msg=Cash");
            }
        }

        /// <summary>
        /// 商户提现不用复核
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_tixian_shanghu_returnbg(pagebase pb)
        {
            RetMerCash objrev = new RetMerCash();
            //后台调用，最终要打印出来参数
            core_huifu.ReturnUrl(HttpContext.Current, "RECV_ORD_ID", objrev, true);
            
            //代表成功！
            if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
            {
                //提现成功。判断这条流水是否已经被处理，已经被处理，不能再重复处理
                //减少用户的资金
                //设置资金的标示
                huifu_tixian_shanghu_fun(objrev);
            }
        }
        /// <summary>
        /// 提现成功调用的方法
        /// </summary>
        /// <param name="objrev"></param>
        static void huifu_tixian_shanghu_fun(RetMerCash objrev)
        {
            supermodel Mdrawmoney = supermodel.create("Mdrawmoney");
            Mdrawmoney["OpenAcctId"] = objrev.OpenAcctId + "";
            Mdrawmoney["OpenBankId"] = objrev.OpenBankId + "";
            //data["DcFlag"] = DateTime.Now;
            Mdrawmoney["Mdrawmoneyid"] = objrev.MerPriv + "";
            Mdrawmoney["TrxId"] = objrev.OrdId + "";
            Mdrawmoney["LogType"] = "1";
            Mdrawmoney["MerCustId"] = objrev.MerCustId + "";
            Mdrawmoney["UsrCustId"] = objrev.UsrCustId + "";

            Mdrawmoney.saveorupdate();
        }

        /// <summary>
        /// 用户提现返回统一调用方法
        /// </summary>
        /// <param name="objrev"></param>
        /// <returns></returns>
        static string huifu_tixian_fun(RetCash objrev)
        {
            supermodel Mdrawmoney = supermodel.create("Mdrawmoney");
            Mdrawmoney["OpenAcctId"] = objrev.OpenAcctId + "";
            Mdrawmoney["OpenBankId"] = objrev.OpenBankId + "";
            //data["DcFlag"] = DateTime.Now;
            Mdrawmoney["Mdrawmoneyid"] = objrev.MerPriv + "";
            Mdrawmoney["TrxId"] = objrev.OrdId + "";
            Mdrawmoney["LogType"] = "1";
            Mdrawmoney["MerCustId"] = objrev.MerCustId + "";
            Mdrawmoney["UsrCustId"] = objrev.UsrCustId + "";
            Mdrawmoney.saveorupdate();
            return objrev.MerPriv;
        }


        /// <summary>
        /// 提现成功显示页面
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_tixian_submit_return(pagebase pb)
        {
            RetCash objrev = new RetCash();
            //后台调用，最终要打印出来参数
            core_huifu.ReturnUrl(HttpContext.Current, "OrdId", objrev, false);
           
            //代表成功！
            if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
            {

                //取现成功。判断这条流水是否已经被处理，已经被处理，不能再重复处理
                //objsend.MerPriv这个就是取现流水的ID
                //减少用户的资金
                //设置资金的标示
                string Mdrawmoneyid = huifu_tixian_fun(objrev);
                //判断金额小于1W 自动复核
                if (Decimal.Parse(objrev.TransAmt) <= Decimal.Parse(HuiFuArg.CashAudit))
                {
                    //提现复核
                    huifu_tixianfuhe(objrev);
                }
                else
                {
                    //没有自动复核，资金冻结
                    huifu_dongjiejine(objrev.UsrCustId, objrev.TransAmt, Mdrawmoneyid.toint32(0));
                }
                //JSHelper.Redirect("/PUser/message.html?status=1&msg=Cash");
            }
            else
            {
                //JSHelper.Redirect("/PUser/message.html?status=0&msg=Cash");
            }
        }

        /// <summary>
        /// 提现复核汇付后台调用信息。
        /// </summary>
        /// <param name="pb"></param>
        public static void huifu_tixian_submit_returnbg(pagebase pb)
        {            
            RetCash objrev = new RetCash();
            //后台调用，最终要打印出来参数
            core_huifu.ReturnUrl(HttpContext.Current, "OrdId", objrev, true);

            if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
            {
                //提现成功。判断这条流水是否已经被处理，已经被处理，不能再重复处理
                //减少用户的资金
                //设置资金的标示
                string Mdrawmoneyid = huifu_tixian_fun(objrev);
                //判断金额小于1W 自动复核
                if (Decimal.Parse(objrev.TransAmt) <= Decimal.Parse(ConfigurationManager.AppSettings["CashAudit"].tostr()))
                {
                    huifu_tixianfuhe(objrev);
                }
                else
                {
                    //没有自动复核，资金冻结
                    //dongjiejine(objrev.UsrCustId, objrev.TransAmt, Mdrawmoneyid);
                }
            }
        }
                
        #endregion 取现部分.e
    }
}